# FTP 应用层自定义协议
'''
1. 高大上版: 自定制报头
dic = {'filename': XX, 'md5': 654654676576776, 'total_size': 26743}
2. 高大上版:可以解决文件过大的问题.


'''
# import struct

# ret = struct.pack('Q',21321432423544354365563543543543)
# print(ret)

import socket
import subprocess
import struct
import json
phone = socket.socket()

phone.bind(('127.0.0.1',8848))

phone.listen(2)
# listen: 2 允许有两个客户端加到半链接池，超过两个则会报错

while 1:
    conn,addr = phone.accept()  # 等待客户端链接我,阻塞状态中
    # print(f'链接来了: {conn,addr}')

    while 1:
        try:

            from_client_data = conn.recv(1024)  # 接收命令


            if from_client_data.upper() == b'Q':
                print('客户端正常退出聊天了')
                break

            obj = subprocess.Popen(from_client_data.decode('utf-8'),
                                   shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,

                                   )
            result = obj.stdout.read() + obj.stderr.read()
            total_size = len(result)

            # 1. 自定义报头
            head_dic = {
                'file_name': 'test1',
                'md5': 6567657678678,
                'total_size': total_size,

            }
            # 2. json形式的报头
            head_dic_json = json.dumps(head_dic)

            # 3. bytes形式报头
            head_dic_json_bytes = head_dic_json.encode('utf-8')

            # 4. 获取bytes形式的报头的总字节数
            len_head_dic_json_bytes = len(head_dic_json_bytes)

            # 5. 将不固定的int总字节数变成固定长度的4个字节
            four_head_bytes = struct.pack('i',len_head_dic_json_bytes)

            # 6. 发送固定的4个字节
            conn.send(four_head_bytes)

            # 7. 发送报头数据
            conn.send(head_dic_json_bytes)

            # 8. 发送总数据
            conn.send(result)

        except ConnectionResetError:
            print('客户端链接中断了')
            break
    conn.close()
phone.close()



import json
import struct
dic = {'filename': 'test1',
       'md5': 654654676576776,
       'total_size': 1024*1024*1024*1024*1024*1024*1024}

dic_json_bytes = json.dumps(dic).encode('utf-8')
# print(dic_json_bytes)
len_dic_json_bytes = len(dic_json_bytes)
print(len_dic_json_bytes)
print(struct.pack('i',len_dic_json_bytes))
print(struct.pack('Q',1024*1024*1024*1024*1024*1024*1024))































